<?php
namespace Lonicera;
use Lonicera\core\Route;
//框架核心入口 每次请求都会创建Lonicera类的对象
class Lonicera{
	private $route;
	//protected $_config = [];
	public $param = array();
    //public function __construct($config)
    //{
    //   $this->_config = $config;
    //}
	
	public function run()
	{
		require_once _SYS_PATH.'core/Loader.php';
		//require_once _SYS_PATH.'core/Route.php';
		spl_autoload_register(['Lonicera\core\Loader', 'loadLibClass']);
		$this->route();
		$this->dispatch();
		//echo 'Hello world';
		//print_r($GLOBALS);exit;
	}

	public function route()
	{
		$this->route = new core\Route();
		$this->route->init();
		
	}
	
	/*
	public function dispatch()
	{
		$controlName = $this->route->control . 'Controller';
		$actionName = $this->route->action . 'Action';
		$path = _APP.$this->route->group.DIRECTORY_SEPARATOR . 'module';
		$path .= DIRECTORY_SEPARATOR.'controller'.DIRECTORY_SEPARATOR.$controlName.'.php';
		// echo $path;
		 
		require_once $path;
		$methods = get_class_methods($controlName); //可能会用到reflect 反射的一些东西
		//print_r($methods);
		if(! in_array($actionName, $methods, TRUE)){
			throw new Exception(sprintf('方法名%s->%s 不存在或非 public' , $controlName, $actionName));
		}
		
		$handler = new $controlName();
		$reflectedClass = new ReflectionClass('Controller');
		$reflectedProperty = $reflectedClass->getProperty('route');
		$reflectedProperty->setAccessible(true);
		$reflectedProperty->setValue($this->route);
		
		//$handler->param = $this->param;
		$handler->{$actionName}(); //如果方法名是字符串拼凑而成可以使用花括号{}括住方法名
	}*/
	//改进
	public function dispatch()
	{
		$controlName = ucfirst($this->route->control) . 'Controller';
		$actionName = $this->route->action . 'Action';
		$group = $this->route->group;
		$className = "app\\{$group}\module\controller\\{$controlName}";
		
		/*
		$path = _APP.$this->route->group.DIRECTORY_SEPARATOR . 'module';
		$path .= DIRECTORY_SEPARATOR.'controller'.DIRECTORY_SEPARATOR.$controlName.'.php';
		// echo $path;
		 
		require_once $path;
		*/
		//$methods = get_class_methods($controlName); //可能会用到reflect 反射的一些东西
		$methods = get_class_methods($className); //可能会用到reflect 反射的一些东西
		//print_r($methods);
		if(! in_array($actionName, $methods, TRUE)){
			throw new \Exception(sprintf('方法名%s->%s 不存在或非 public' , $controlName, $actionName));
		}
		
		$handler = new $className();
		$reflectedClass = new \ReflectionClass('Lonicera\core\Controller');
		$reflectedProperty = $reflectedClass->getProperty('route');
		$reflectedProperty->setAccessible(true);
		$reflectedProperty->setValue($this->route);
		
		//$handler->param = $this->param;
		$handler->{$actionName}(); //如果方法名是字符串拼凑而成可以使用花括号{}括住方法名
	}
}

function dump($keyArray){
	echo '<pre>';
	print_r($keyArray); //可以写个dump,能不能使用主要看是否已经加载
	echo '<pre>';
}
?>